package com.party.web.web.controller.activity;

import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.redis.StringJedis;
import com.party.common.utils.LangUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.activity.ActivityDetail;
import com.party.core.model.activity.ActivityWithMemberPartner;
import com.party.core.model.copartner.TargetCopartner;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.crowdfund.CrowdfundEvent;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.member.ThirdMember;
import com.party.core.service.activity.IActivityDetailService;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.activity.biz.ActivityDetailBizService;
import com.party.core.service.activity.biz.ActivityInfoBizService;
import com.party.core.service.activity.biz.CrowfundResourceBizService;
import com.party.core.service.copartner.ITargetCopartnerService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IThirdMemberService;
import com.party.core.service.cos.CosBizService;
import com.party.web.biz.activity.ActivityBizService;
import com.party.web.biz.file.FileBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.web.utils.RealmUtils;
import com.party.web.web.annotation.ControlParam;
import com.party.web.web.annotation.DataControl;
import com.party.web.biz.system.member.MemberGroupBizService;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.dto.output.activity.ActivityOutput;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author： yifeng
 * @description： 众筹项目控制器
 * @date：Created in  2017/12/20 下午 18:57
 **/
@Controller
@RequestMapping("activity/zcActivity")
public class ZcActivityController {

    @Value("#{party['mic.url']}")
    private String micUrl;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private IActivityDetailService activityDetailService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private ICrowdfundEventService crowdfundEventService;
    @Autowired
    private ActivityDetailBizService activityDetailBizService;
    @Autowired
    private CrowfundResourceBizService crowfundResourceBizService;
    @Autowired
    private IThirdMemberService thirdMemberService;
    @Autowired
    private MemberGroupBizService memberGroupBizService;
    @Autowired
    private StringJedis stringJedis;
    @Autowired
    private ActivityBizService activityBizService;
    @Autowired
    private CosBizService cosBizService;
    @Autowired
    private ITargetCopartnerService targetCopartnerService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private ActivityInfoBizService activityInfoBizService;
    @Autowired
    private ICounterfoilService counterfoilService;
    @Autowired
    private IProjectService projectService;

    protected static Logger logger = LoggerFactory.getLogger(ZcActivityController.class);

    /**
     * 发布保存
     *
     * @param activity
     * @param activityDetail
     * @param result
     * @return
     * @throws Exception
     */
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping(value = {"save", "/third/save"})
    public AjaxResult save(Activity activity, ActivityDetail activityDetail, BindingResult result, String picList, String videoList, ThirdMember thirdMember) {
        try {
            // 数据验证
            if (result.hasErrors()) {
                List<ObjectError> allErros = result.getAllErrors();
                return AjaxResult.error(allErros.get(0).getDefaultMessage());
            }
            if (StringUtils.isEmpty(activity.getEventId())) {
                return AjaxResult.error("主题不能为空");
            }

            CrowdfundEvent crowdfundEvent = crowdfundEventService.get(activity.getEventId());
            if (crowdfundEvent == null) {
                return AjaxResult.error("主题不能为空");
            }
            String memberId = StringUtils.isEmpty(crowdfundEvent.getCreateBy()) ? RealmUtils.getCurrentUser().getId() : crowdfundEvent.getCreateBy();
            ActivityDetail detail = activityDetailService.getByRefId(crowdfundEvent.getId());
            if (detail == null) {
                return AjaxResult.error("主题不能为空");
            } else {
                activityDetailBizService.castToHTML(detail);
            }
            List<Counterfoil> counterfoils = counterfoilService.findByBusinessId(crowdfundEvent.getId(), Constant.BUSINESS_TYPE_CROWDFUND);
            if (counterfoils.size() > 0) {
                activity.setPrice(counterfoils.get(0).getPayment());
                activity.setLimitNum(counterfoils.get(0).getLimitNum());
            } else {
                activity.setPrice(crowdfundEvent.getPrice());
                activity.setLimitNum(crowdfundEvent.getLimitNum());
            }
            activity.setStartTime(crowdfundEvent.getStartTime());
            activity.setEndTime(crowdfundEvent.getEndTime());
            activity.setCityId(crowdfundEvent.getCityId());
            activity.setArea(crowdfundEvent.getArea());
            activity.setPlace(crowdfundEvent.getPlace());
            activity.setLat(crowdfundEvent.getLat());
            activity.setLng(crowdfundEvent.getLng());

            activityDetail.setApplyRelated(detail.getApplyRelated());
            activityDetail.setMatchStandard(detail.getMatchStandard());

            activity.setTitle(activity.getTitle().replace("\"", "“"));
            if (StringUtils.isNotEmpty(activity.getId())) {
                // 更新内容
                Activity t = activityService.get(activity.getId());// 从数据库取出记录的值
                MyBeanUtils.copyBeanNotNull2Bean(activity, t);// 将编辑表单中的非NULL值覆盖数据库记录中的值
                activityService.update(t);// 保存

                if (activity.getEditShare() != null) {
                    if (activity.getEditShare() == 1) {
                        ThirdMember unique = thirdMemberService.findByTargetId(activity.getId());
                        if (unique == null) {
                            unique = new ThirdMember();
                            MyBeanUtils.copyBeanNotNull2Bean(thirdMember, unique);
                            unique.setId(null);
                            unique.setPublisher(memberId);
                            unique.setTargetId(activity.getId());
                            thirdMemberService.insert(unique);
                        } else {
                            if (!thirdMember.getAccount().equals(unique.getAccount())) {
                                unique.setAccount(thirdMember.getAccount());
                                unique.setPassword(thirdMember.getPassword());
                                thirdMemberService.update(unique);
                            }
                        }
                        List<String> uriAll = thirdMemberService.allURI();
                        stringJedis.setValue("thirdMemberList", uriAll.toString());
                        memberGroupBizService.saveThirdMember();
                    } else if (activity.getEditShare() == 2) {
                        thirdMemberService.deleteByTargetId(activity.getId());
                    }
                }
            } else {// 新增表单保存
                activity.setMember(memberId); // 当前用户
                activity.setIsCopartner(2); // 不是合伙人
                activity.setIsOpen(1); // 报名开启
                activity.setShareNum(0); // 分享数
                activity.setReadNum(0); // 阅读数
                activity.setJoinNum(0); // 报名数
                activity.setGoodNum(0); // 点赞数
                activity.setCheckStatus("1"); // 默认审核成功
                activity.setMicWebStatus(1); // 微网站效果
                activity.setInviteOnly(0); // 是否持邀请码参与
                activity.setIsAllowedOutside(0); // 是否允许在其它城市频道显示
                activity.setShowFront(1); // 显示在前端
                activity.setEditShare(YesNoStatus.NO_NEW.getCode());
                activity.setCrowdfundHintSwitch(YesNoStatus.NO.getCode());
                activityService.insert(activity);// 保存
            }

            /************* 详情 ****************/
            activityDetailBizService.saveBiz(activity.getId(), activityDetail);
            crowfundResourceBizService.saveResourceBiz(activity.getId(), picList, videoList, memberId);

            activityInfoBizService.saveBiz(activity.getId());

            try {
                String filePath = fileBizService.getUploadCIPath(memberId, "zcActivity");
                /*** 众筹联合发起二维码 ***/
                String dyFileName = "dy_" + activity.getId();
                String dyContent = "project/target_detail.html?id=" + activity.getId();
                fileBizService.uploadCloudOut(dyFileName, filePath, dyContent, memberId);

                /*** 众筹项目详情二维码 ***/
                String xqFileName = "detail_" + activity.getId();
                String detailContent = "project/target_client_detail.html?id=" + activity.getId();
                fileBizService.uploadCloudOut(xqFileName, filePath, detailContent, memberId);

                /*** 直接众筹项目详情二维码 ***/
                String dpXqFileName = "directPay_" + activity.getId();
                String dpDetailContent = "project/target_client_detail.html?id=" + activity.getId() + "&dp=1";
                fileBizService.uploadCloudOut(dpXqFileName, filePath, dpDetailContent, memberId);
            } catch (Exception e) {
                logger.error("众筹项目二维码生成异常", e);
            }

            //修改project冗余字段title
            try {
                projectService.updateProjectTitle(activity.getId());
            } catch (Exception e) {
                logger.error("activity保存——————修改project冗余字段title异常", e.getMessage());
            }

            return AjaxResult.success("众筹保存成功", activity.getId());
        } catch (Exception e) {
            logger.error("众筹保存失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存失败");
        }
    }


    /**
     * 生成分享相关信息
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("generateInfo")
    public AjaxResult generateInfo(String id) {
        Map<String, Object> result = activityBizService.generateInfo(id);
        return AjaxResult.success(result);
    }

    /**
     * 第三方用户编辑
     *
     * @param id
     * @return
     */
    @RequestMapping("third/editCrowdActivity")
    public ModelAndView editCrowdfundActivity(String id) {
        ModelAndView mv = new ModelAndView("activity/editZcAct");
        if (StringUtils.isNotEmpty(id)) {
            /** 活动 **/
            Activity activity = activityService.get(id);
            mv.addObject("activity", activity);
            /** 活动详情 **/
            ActivityDetail activityDetail = activityDetailService.getByRefId(activity.getId());
            if (activityDetail != null) {
                activityDetailBizService.castToHTML(activityDetail);
            }
            mv.addObject("activityDetail", activityDetail);
        }
        return mv;
    }

    /**
     * 众筹项目列表（合伙人）
     *
     * @param activity
     * @param page
     * @param commonInput
     * @return
     */
    @RequestMapping(value = "zcActivityCopartnerList")
    public ModelAndView zcActivityList(ActivityWithMemberPartner activity, BindingResult result, Page page, CommonInput commonInput) {
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
        }
        Subject subject = SecurityUtils.getSubject();
        ModelAndView mv = new ModelAndView("activity/zcActivityCopartnerList");
        MemberGroup user = RealmUtils.getCurrentUser();
        activity.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        activity.setIsCrowdfunded(1);
        activity.setIsCopartner(1);
        Map<String, Object> params = CommonInput.appendParams(commonInput);

        params.put("isMultiple", YesNoStatus.NO.getCode());
        params.put("isCopartner", 1); // 合伙人参与的项目
        params.put("isJoin", 1); // 同意参加推广
        params.put("eventName", activity.getEventName());
        params.put("copartnerId", user.getId());
        mv.addObject("input", commonInput);
        mv.addObject("activity", activity);
        List<ActivityWithMemberPartner> activities = activityService.webListPage(activity, params, page);
        List<ActivityOutput> activityOutputs = LangUtils.transform(activities, input -> {
            String filePath = fileBizService.getUploadCIPath(input.getMemberId(), "zcActivity");
            Map<String, String> qrCodeMap = new HashMap<String, String>();
            ActivityOutput output = ActivityOutput.transform(input);

            // 众筹联合发起二维码
            String dyFileName = "dy_" + input.getId();
            String content = "project/target_detail.html?id=" + input.getId();
            String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + dyFileName);
            qrCodeMap.put("dyQrCode", qrCodeUrl);
            qrCodeMap.put("dyQrCodeContent", micUrl + content);


            Activity addressActivity = new Activity();
            addressActivity.setCityId(input.getCityId());
            addressActivity.setArea(input.getArea());
            addressActivity.setPlace(input.getPlace());
            String address = activityService.getShowAddress(addressActivity);
            output.setPlace(address);

            // 众筹项目详情二维码
            String detailFileName = "detail_" + input.getId();
            String detailContent = "project/target_client_detail.html?id=" + input.getId();
            String detailQrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + detailFileName);
            qrCodeMap.put("detailQrCode", detailQrCodeUrl);
            qrCodeMap.put("detailQrCodeContent", micUrl + detailContent);

            output.setQrCodeMap(qrCodeMap);
            return output;
        });
        mv.addObject("activities", activityOutputs);
        mv.addObject("page", page);
        return mv;
    }

    /**
     * 众筹项目详情（合伙人）
     *
     * @param actId 活动id
     * @return
     */
    @DataControl
    @RequestMapping(value = "zcActivityCopartnerDetail")
    public ModelAndView zcActivityDetail(@ControlParam(table = "co_target_copartner", column = "partner_id") String actId) {
        ModelAndView mv = new ModelAndView("activity/zcActivityCopartnerDetail");
        Activity activity = activityService.get(actId);
        TargetCopartner targetCopartner = targetCopartnerService.findByTargetId(actId);
        ActivityDetail activityDetail = activityDetailService.getByRefId(actId);
        if (activityDetail != null) {
            activityDetailBizService.castToHTML(activityDetail);
        }
        String address = activityService.getShowAddress(activity);
        mv.addObject("address", address);
        mv.addObject("targetCopartner", targetCopartner);
        mv.addObject("activity", activity);
        mv.addObject("activityDetail", activityDetail);
        return mv;
    }

    /**
     * 添加合作渠道
     *
     * @param activityId 活动id
     * @return
     */
    @RequestMapping("toFormCooperateChannel")
    public ModelAndView toFormCooperateChannel(String activityId) {
        ModelAndView mv = new ModelAndView("activity/cooperateChannelView");
        Activity activity = activityService.get(activityId);
        if (StringUtils.isNotEmpty(activity.getCosponsorId())) {
            MemberGroup member = memberGroupService.get(activity.getCosponsorId());
            mv.addObject("member", member);
        }
        mv.addObject("activityId", activityId);
        return mv;
    }

    /**
     * 添加合作渠道
     *
     * @param activityId  活动id
     * @param mobile      手机号
     * @param countryCode 区号
     * @return
     */
    @ResponseBody
    @RequestMapping("bindRelationZcActivity")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult bindRelationZcActivity(String activityId, String mobile, String countryCode) {
        if (StringUtils.isEmpty(activityId)) {
            return AjaxResult.error("活动id不能为空");
        }
        if (StringUtils.isEmpty(mobile)) {
            return AjaxResult.error("手机号不能为空");
        }
        try {
            countryCode = "+86";
            activityBizService.bindZcActivityRelation(activityId, mobile, countryCode);
            return AjaxResult.success();
        } catch (BusinessException e) {
            logger.error("添加合作渠道异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("添加合作渠道异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("添加合作渠道异常");
        }
    }
}
